//
//  HGAVPlayerManager.m
//  悦享
//
//  Created by dllo on 16/3/22.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "HGAVPlayerManager.h"
#import <AVFoundation/AVFoundation.h>

@interface HGAVPlayerManager ()



@end

@implementation HGAVPlayerManager


//单例
+ (HGAVPlayerManager *)shareHGavPlayerManager{
    static HGAVPlayerManager *HGplayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        HGplayer = [[HGAVPlayerManager alloc] init];
        HGplayer.avPlayer = [[AVPlayer alloc] init];//初始化音乐播放器
        HGplayer.avPlayer.volume = 3.0f;//音量属性
        HGplayer.isPlay = NO;
        HGplayer.index = -1;
        
    });
    
    return HGplayer;
}

//重写init初始化方法
- (instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

- (void)playToEnd{
    //确保block存在（安全判断）
    if (self.playToEndBlock) {
        self.playToEndBlock();//回调block
    }
}


- (void)playMusicWithUrl:(NSString *)url{
    
    //安全判断
    if (!url) {
        return;
    }
    
    //如果存在当前磁带， 移除
    if (self.avPlayer.currentItem) {
        [self.avPlayer.currentItem removeObserver:self forKeyPath:@"status"];//移除当前， 也就是移除当前监听
    }
    
    //磁盘（磁带：播放地址 放入磁盘）
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    //监听啥时候播放
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    //给音乐播放器添加磁盘
    [self.avPlayer replaceCurrentItemWithPlayerItem:item];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    //new代表改变后的新值（监听传值）
    AVPlayerItemStatus status = [change[@"new"] integerValue];
    
    switch (status) {
        case AVPlayerItemStatusReadyToPlay://当status为播放状态时；
        {
            //当前播放音乐的总时长(秒) = 总播放的长度 除以 每一帧时间
            _sumTime = self.avPlayer.currentItem.duration.value / self.avPlayer.currentItem.duration.timescale;
            
            [self play];
        }
            break;
            
        default:
        {
            NSLog(@"错误!!");
        }
            break;
    }
}

//播放
- (void)play{
    
    [self.avPlayer play];//这就是风装思想
    self.isPlay = YES;//当前为播放状态
    
    //安全判断
    if (self.timer == nil) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playTimer) userInfo:nil repeats:YES];//每0.1秒就调用这个selector
    }
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];//将定时器加入runloop中，（我们可以理解为:闭合的回路，让它一直执行这个方法）//现在我们在滑动视图的时候，图片就还在旋转,滑竿就还在滑动.
    //主线程默认开启，子线程默认关闭的
    
    
}

//没0.1秒调用
- (void)playTimer{
    //计算当前播放了多少秒
    CGFloat timer = _avPlayer.currentTime.value / _avPlayer.currentTime.timescale;
    
    if (self.playTimerBlock) {
        self.playTimerBlock(timer);//把这个时间传出去
    }
}

//暂停
- (void)pause{
    [self.avPlayer pause];
    
    self.isPlay = NO;//当前为停止状态
    
    //安全判断
    if (self.timer) {
        [self.timer invalidate]; //销毁定时器
        self.timer = nil;//把这个控件释放， 指回空
    }
}


//魔一时刻开始播放
- (void)seekToTime:(CGFloat)time{
    //封装优化
    [self pause];
    
    //魔一时间 播放的    进度(可以理解为:第一个参数为当前时间 乘 第二个参数每一秒走多少进度 = 进度)
    
    [self.avPlayer seekToTime:CMTimeMakeWithSeconds(time * _sumTime, self.avPlayer.currentTime.timescale)
    completionHandler:^(BOOL finished) {
       //time * _sumtime计算时间
        if (finished) {
            [self play]; //找到节点成功后  播放
        }
    }];
}
//重写setVolime

- (void)setVolume:(CGFloat)volume{
    _avPlayer.volume = volume;
}

//重写getVolume

- (CGFloat)volume{
    return  _avPlayer.volume;
}



#pragma mark-视频方面
/**
 *  根据一个网址去创建播放器
 *
 *  @return
 */
+ (HGAVPlayerManager *)shareHGVideoPlayerManager{
    static HGAVPlayerManager *HGplayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        HGplayer = [[HGAVPlayerManager alloc] init];
        HGplayer.avPlayer = [[AVPlayer alloc] init];//初始化音乐播放器
        HGplayer.avPlayer.volume = 3.0f;//音量属性
        HGplayer.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SREEN_WIDTH, 200)];
        HGplayer.playerLayer = [[AVPlayerLayer alloc] init];
        
    });
    
    return HGplayer;
    
    
}




/**
 *  vedioPlayer播放
 *
 *  @param url
 *
 *  @return
 */
- (UIView *)createAvPlayerWithUrl:(NSString *)url{
    
    
    
    
    //安全转码
    NSString *resultUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //转化成url
    NSURL *url1 = [NSURL URLWithString:resultUrl];
    
    //创建播放项目对象
    self.playerItem = [AVPlayerItem playerItemWithURL:url1];
    
    //播放器添加项目对象
    [_avPlayer replaceCurrentItemWithPlayerItem:_playerItem];
    //创建承载播放器的layer
    //    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
    self.playerLayer.player = _avPlayer;
    
    self.playerLayer.frame = CGRectMake(0, 0, SREEN_WIDTH, 200);
    //设置视频的填充模式
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [self.playView.layer insertSublayer:self.playerLayer atIndex:0];
    _playView.backgroundColor = [UIColor blackColor];
    return _playView;
    
}


@end
